package com.jxit0573.android.lib.util;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.jxit0573.android.lib.R;
import com.jxit0573.android.lib.impl.OnActionListener;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

/**
 * @author jia
 */
public class DialogUtils {

    private static volatile DialogUtils instance;

    private static Dialog dialog = null;
    private static long lastTime = 0;

    private DialogUtils() {
    }

    public static DialogUtils getInstance() {
        if (instance == null) {
            synchronized (DialogUtils.class) {
                if (instance == null) {
                    instance = new DialogUtils();
                }
            }
        }
        return instance;
    }

    public void showLoading(Context context, final String text) {
        closeDialog();
        BackgroundTasks.getInstance().post(() -> {
            dialog = new QMUITipDialog.Builder(context)
                    .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                    .setTipWord(text)
                    .create(false);
            dialog.show();
        });
    }

    public void showLoading(Context context) {
        showLoading(context, ResourceUtils.getString(context, R.string.loading));
    }

    public void showSingleChoice(Context context, CharSequence[] items, DialogInterface.OnClickListener listener) {
        closeDialog();
        dialog = new QMUIDialog.MenuDialogBuilder(context)
                .addItems(items, listener)
                .create();
        dialog.show();
    }

    public void showMessage(Context context, final String msg, final OnActionListener listener) {
        closeDialog();
        QMUIDialog.MessageDialogBuilder builder = new QMUIDialog.MessageDialogBuilder(context);
        builder.setMessage(msg);
        builder.addAction("取消", (dialog, index) -> {
            dialog.dismiss();
            if (listener != null) {
                listener.onCancel();
            }
        }).addAction("确定", (dialog, index) -> {
            dialog.dismiss();
            if (listener != null) {
                listener.onConfirm(msg);
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    /**
     * 关闭弹出框
     */
    public void closeDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        dialog = null;
    }

}
